<?php

namespace app\task\cron;

use yunwuxin\cron\Task;
use think\facade\Db;

/**
 * 话费供应商余额快照.【每天 23:59 生成】
 */
class MobileSupplierBalanceSnapshot extends Task
{
    public function configure()
    {
        // 分 时 日 月 周
        $this->expression = '59 23 * * *';
    }

    protected function handle()
    {
        echo '供应商余额快照开始--' . date('Y-m-d H:i:s') . PHP_EOL;
        $lockKey = 'mobile_supplier_balance_snapshot_lock_key';
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理呢' . PHP_EOL;

            return true;
        }

        cache($lockKey, 1, 120);

        $today = date('Y-m-d');
        $exists = Db::name('mobile_supplier_daily_balance')
            ->where('dateymd', $today)
            ->value('id');
        if ($exists) {
            echo '执行过了...' . PHP_EOL;
            return true;
        }

        $list = Db::name('mobile_supplier')
            ->field('id, code, url, app_id, app_secret, balance')
            ->where('is_deleted', 0)
            ->where('is_main', 1)
            ->select()
            ->toArray();
        $supplier = [];
        foreach ($list as $info) {
            // 接口调用，获取最新的价格
            try {
                if (false === strpos($info['code'], '\\')) {
                    $code = explode('-', $info['code'])[0]; // lechong，lechong-1024 都调用 \api\mobile\Lechong 这个类
                    $class = '\\api\\mobile\\' . ucfirst($code);
                } else {
                    $class = $info['code'];
                }
                if (class_exists($class)) {
                    $model = new $class($info);
                    $balance = $model->queryAmount();
                    if (false !== $balance) {
                        $info['balance'] = $balance;
                    }
                }
            } catch (\Exception $e) {
                echo $e->getMessage() . PHP_EOL;
            }

            $supplier[] = [
                'dateymd' => $today,
                'supplier_id' => $info['id'],
                'balance' => $info['balance'],
            ];
        }
        if ($supplier) {
            Db::name('mobile_supplier_daily_balance')
                ->insertAll($supplier);
        }

        cache($lockKey, null);

        echo '供应商余额快照结束--' . date('Y-m-d H:i:s') . PHP_EOL;
    }
}
